//
//  TimelineCellPictureView.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/18.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit
let PictureMargin : CGFloat = 5
private let pictureViewCellID = "pictureViewCellID"
class TimelineCellPictureView: UICollectionView {

    var imageURLs : [NSURL]? {
        didSet {
            let sizeP = calculateSize()
            
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(sizeP)
            }
            
            testLabel.text = "\(imageURLs?.count ?? 0)"
            
            reloadData()
        }
        
        
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
//        let layout = UICollectionViewLayout()
        let layout = UICollectionViewFlowLayout()//flow流水布局的layout才又itemsize属性
        layout.minimumInteritemSpacing = PictureMargin
        layout.minimumLineSpacing = PictureMargin
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        
        //注册类
        registerClass(pictureCell.self, forCellWithReuseIdentifier: pictureViewCellID)
        //数据源设置成自己
        self.dataSource = self
        self.delegate = self
        //让图片collectionView的滚动到顶部的功能为false(当试图里有且仅有1个滚动试图时候才能直接到顶部,所以禁了这个,tableView就可以)
        self.scrollsToTop = false
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
//        addSubview(testLabel)
//        
//        testLabel.snp_makeConstraints { (make) -> Void in
//            make.centerY.equalTo(self.snp_centerY)
//            make.centerX.equalTo(self.snp_centerX)
//        }
        
        backgroundColor = UIColor.whiteColor()
    }
    
    //计算配图到底该多大?
    private func calculateSize() -> CGSize
    {
        let imageCount = imageURLs?.count ?? 0
        //一行3张时候的item宽度
        let maxWidth = ScreenW - 2 * TimelineCellMargin
        let itemWidth = (maxWidth - 2*PictureMargin)/3.000001//解决iPhone6+显示的问题
        
        //设置item的size
       let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        if imageCount == 0
        {
            return CGSizeZero
        }else
        if imageCount == 1
        {
            //TODO: 单张应该按图片大小来
            var imageSize = CGSize(width: 180, height: 120)
            //从缓存中拿到图片
            let key = imageURLs?.last?.absoluteString
            
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            //设置单张图片的大小
            if image != nil {
                imageSize = image.size
            }
            layout.itemSize = imageSize
            return imageSize
        }else
        if imageCount == 4
        {
            let w = itemWidth * 2 + PictureMargin
            let imageSize = CGSize(width: w, height: w)
            return imageSize
        }
//        if imageCount == 2
//        {
//            let imageSize = CGSize(width: itemWidth*2 + PictureMargin, height: itemWidth)
//            return imageSize
//        }
        //如果是其他的多张图片
//        let column : CGFloat = (imageURLs?.count)! > 2 ? 3 : 2
        
        let row = CGFloat( (imageCount - 1) / 3 + 1)
        
        let imageSize = CGSize(width: maxWidth, height: itemWidth * row + (row-1)*PictureMargin)
        
        return imageSize
    }
    
    //加测试label
    private lazy var testLabel = UILabel(title: "", color: UIColor.redColor(), fontSize: 18)

}

//MARK: 让View遵守数据源协议
extension TimelineCellPictureView : UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        print(imageURLs?.count)
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellID, forIndexPath: indexPath) as! pictureCell
        
        cell.imageURL = imageURLs![indexPath.item]
//        cell.backgroundColor = UIColor.randomColor()
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.imageCount = imageURLs?.count ?? 0
        
        photoBrowser.currentImageIndex = indexPath.item
        
        photoBrowser.delegate = self
        
        photoBrowser.show()
        /*
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        
        browser.sourceImagesContainerView = 原图的父控件;
        
        browser.imageCount = 原图的数量;
        
        browser.currentImageIndex = 当前需要展示图片的index;
        
        browser.delegate = 代理;
        
        [browser show]; // 展示图片浏览器
        

        */
    }
}
//MARK: 显示图片的框架代理
extension TimelineCellPictureView : SDPhotoBrowserDelegate {
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        if let placeHolderStr = imageURLs?[index].absoluteString {
            
            let highQualityStr = placeHolderStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
            
            return NSURL(string: highQualityStr)
            
        }
                return nil

    }
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        
        if let cell = self.cellForItemAtIndexPath(indexPath) as? pictureCell {
            return cell.iconView.image
        }
        return nil
    }
}

// MARK: 自定义的cell
class pictureCell: UICollectionViewCell {
    var imageURL : NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL!)

//            imageView.sizeToFit()
            iconView.backgroundColor = UIColor.randomColor()
//            self.backgroundView = imageView
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(iconView)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(snp_edges)
        }
    }
    
     private lazy var iconView : UIImageView = {
        let iv = UIImageView()
        
        //用ScaleAspectFit,图片不会被拉伸变形
        iv.contentMode = UIViewContentMode.ScaleAspectFill//ScaleAspectFill是以最短边填充,fit是以最长边填充
        //超出部分裁剪掉
        iv.clipsToBounds = true
        
        return iv
    }()
}
